﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace Core.Util
{
    /// <summary>
    /// 日志处理
    /// </summary>
    public class FileObj
    {
       
        #region 记录异常日志日志
        /// <summary>
        /// 记录异常日志，文件名ExLogs.txt,格式时间+位置+错误信息+错误明细
        /// </summary>
        /// <remarks>
        /// 创建时间：2017-11-30
        /// 创建者：xujiangbo
        /// </remarks>
        /// <example>
        /// <code>
        /// ExLogs(ex);
        /// </code>
        /// </example>
        /// <param name="ex">异常信息Exception</param>
        /// <retuns>无</retuns>
        public static void ExLogs(Exception ex)
        {

            string Path = GetRootPath() + "\\ExLogs.txt";
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.GetEncoding("utf-8"));
            f2.WriteLine("[错误时间]：" + DateTime.Now);
            f2.WriteLine("[Message]：" + ex.Message);
            f2.WriteLine("[Source]：" + ex.Source);
            f2.WriteLine("[InnerException]：" + ex.InnerException);
            f2.WriteLine("[StackTrace]：" + ex.StackTrace);
            f2.WriteLine("————————————————————————————————————");
            f2.Close();
            f2.Dispose();
        }
        #endregion

        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }
    }
}
